package cn.wl.hrm.service.impl;

import cn.wl.hrm.domain.Employee;
import cn.wl.hrm.domain.Meal;
import cn.wl.hrm.domain.Tenant;
import cn.wl.hrm.dto.TenantEnteringDto;
import cn.wl.hrm.mapper.EmployeeMapper;
import cn.wl.hrm.mapper.TenantMapper;
import cn.wl.hrm.service.IEmployeeService;
import cn.wl.hrm.service.ITenantService;
import cn.wl.hrm.util.encrypt.MD5;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wl
 * @since 2020-04-19
 */
@Service
@Transactional
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public void entering(TenantEnteringDto dto) {
        //获取从前台传来的Tenant对象
        Tenant tenant = dto.getTenant();
        //验证
        if(!StringUtils.hasLength(tenant.getCompanyName())){
            throw new IllegalArgumentException("公司名不能为空");
        }
        if(!StringUtils.hasLength(tenant.getCompanyNum())){
            throw new IllegalArgumentException("公司执照不能为空");
        }
        if(!StringUtils.hasLength(tenant.getAddress())){
            throw new IllegalArgumentException("公司地址不能为空");
        }
        //获取从前台传来的Employee对象
        Employee employee = dto.getEmployee();
        //获取从前台传来的mealId
        Long mealId = dto.getMealId();

        //将tenant添加到数据库
        //为了安全，防止前台传一些其他的字段数据，来恶意更改数据库中tenant表
        //新建一个Tenant对象，将前台传来的对象的值赋值给新的对象
        Tenant newTenant = new Tenant();
        newTenant.setCompanyName(tenant.getCompanyName());
        newTenant.setCompanyNum(tenant.getCompanyNum());
        newTenant.setAddress(tenant.getAddress());
        newTenant.setLogo(tenant.getLogo());
        newTenant.setTenantType(tenant.getTenantType());
        Date date = new Date();
        newTenant.setRegisterTime(date);
        newTenant.setState(Tenant.STATE_NORMAL);
        baseMapper.insert(newTenant);

        //同上，将employee添加到数据库也需要新建一个对象
        Employee newEmployee = new Employee();
        newEmployee.setUsername(employee.getUsername());
        newEmployee.setEmail(employee.getEmail());
        newEmployee.setTel(employee.getTel());
        //对密码进行加密
        String newPassword = MD5.getMD5(employee.getPassword() + "wl");
        newEmployee.setPassword(newPassword);
        newEmployee.setInputTime(date);
        newEmployee.setState(Employee.STATE_NORMAL);
        newEmployee.setTenantId(newTenant.getId());
        newEmployee.setType(Employee.TYPE_ADMIN);
        employeeMapper.insert(newEmployee);

        //添加mealId到tenant和meal的中间表
        baseMapper.insertMealId(mealId,newTenant.getId(), Meal.STATE_UN_PAY);

    }
}
